[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1 Customization

This chapter talks about various topics relevant to adapting the behavior of Emacs in minor ways. See The Emacs Lisp Reference Manual for how to make more far-reaching changes.

All kinds of customization affect only the particular Emacs job that you do them in. They are completely lost when you kill the Emacs job, and have no effect on other Emacs jobs you may run at the same time or later. The only way an Emacs job can affect anything outside of it is by writing a file; in particular, the only way to make a customization ‘permanent’ is to put something in your ‘.emacs’ file or other appropriate file to do the customization in each session. See section The Init File, ‘~/.emacs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 Minor Modes

Minor modes are optional features which you can turn on or off. For example, Auto Fill mode is a minor mode in which <SPC> breaks lines between words as you type. All the minor modes are independent of each other and of the selected major mode. Most minor modes say in the mode line when they are on; for example, ‘Fill’ in the mode line means that Auto Fill mode is on.

Append -mode to the name of a minor mode to get the name of a command function that turns the mode on or off. Thus, the command to enable or disable Auto Fill mode is called M-x auto-fill-mode. These commands are usually invoked with M-x, but you can bind keys to them if you wish. With no argument, the function turns the mode on if it was off and off if it was on. This is known as toggling. A positive argument always turns the mode on, and an explicit zero argument or a negative argument always turns it off.

Enabling or disabling some minor modes applies only to the current buffer; each buffer is independent of the other buffers. Therefore, you can enable the mode in particular buffers and disable it in others.

Auto Fill mode allows you to enter filled text without breaking lines explicitly. Emacs inserts newlines as necessary to prevent lines from becoming too long. @xref{Filling}.

Outline minor mode provides the same facilities as the major mode called Outline mode; but since it is a minor mode instead, you can combine it with any major mode. @xref{Outline Mode}.

Overwrite mode causes ordinary printing characters to replace existing text instead of shoving it over. For example, if the point is in front of the ‘B’ in ‘FOOBAR’, then in Overwrite mode typing a G changes it to ‘FOOGAR’, instead of making it ‘FOOGBAR’ as usual.

Auto Save mode causes the contents of a buffer to be saved periodically to reduce the amount you will lose in case of a system crash. @xref{Auto Save}.

The following minor modes normally apply to all buffers at once. Since each is enabled or disabled by the value of a variable, you can set them differently for particular buffers, by explicitly making the corresponding variables local in those buffers. See section Local Variables.

Abbrev mode allows you to define abbreviations that automatically expand as you type them. For example, ‘amd’ might expand to ‘abbrev mode’. @xref{Abbrevs}, for full information.

Line Number mode enables continuous display in the mode line of the line number of point. @xref{Mode Line}.

Scroll Bar mode gives each window a scroll bar (@pxref{Scroll Bars}). Menu Bar mode gives each frame a menu bar (@pxref{Menu Bars}). Both of these modes are enabled by default when you use the X Window System.

In Transient Mark mode, every change in the buffer “deactivates” the mark, so that commands that operate on the region will get an error. This means you must either set the mark, or explicitly “reactivate” it, before each command that uses the region. The advantage of Transient Mark mode is that Emacs can display the region highlighted (currently only when using X). @xref{Setting Mark}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 Variables

A variable is a Lisp symbol which has a value. The symbol’s name is also called the name of the variable. A variable name can contain any characters that can appear in a file, but conventionally variable names consist of words separated by hyphens. A variable can have a documentation string which describes what kind of value it should have and how the value will be used.

Lisp allows any variable to have any kind of value, but most variables that Emacs uses require a value of a certain type. Often the value should always be a string, or should always be a number. Sometimes we say that a certain feature is turned on if a variable is “non-nil,” meaning that if the variable’s value is nil, the feature is off, but the feature is on for any other value. The conventional value to use to turn on the feature—since you have to pick one particular value when you set the variable—is t.

Emacs uses many Lisp variables for internal recordkeeping, as any Lisp program must, but the most interesting variables for you are the ones that exist for the sake of customization. Emacs does not (usually) change the values of these variables; instead, you set the values, and thereby alter and control the behavior of certain Emacs commands. These variables are called options. Most options are documented in this manual, and appear in the Variable Index (@pxref{Variable Index}).

One example of a variable which is an option is fill-column, which specifies the position of the right margin (as a number of characters from the left margin) to be used by the fill commands (@pxref{Filling}).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.1 Examining and Setting Variables

C-h v var <RET>

Print the value and documentation of variable var (describe-variable).

M-x set-variable <RET> var <RET> value <RET>

Change the value of variable var to value.

To examine the value of a single variable, use C-h v (describe-variable), which reads a variable name using the minibuffer, with completion. It prints both the value and the documentation of the variable. For example,

C-h v fill-column <RET>

prints something like this:

fill-column's value is 75

Documentation:
*Column beyond which automatic line-wrapping should happen.
Automatically becomes buffer-local when set in any fashion.

The star at the beginning of the documentation indicates that this variable is an option. C-h v is not restricted to options; it allows any variable name.

The most convenient way to set a specific option is with M-x set-variable. This reads the variable name with the minibuffer (with completion), and then reads a Lisp expression for the new value using the minibuffer a second time. For example,

M-x set-variable <RET> fill-column <RET> 75 <RET>

sets fill-column to 75.

You can set any variable with a Lisp expression using the function setq. Here’s how to use it to set fill-column:

(setq fill-column 75)

Setting variables, like all means of customizing Emacs except where explicitly stated, affects only the current Emacs session.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.2 Editing Variable Values

These two functions make it easy to display all the user edit options and change some of them.

M-x list-options

Display a buffer listing names, values and documentation of all options.

M-x edit-options

Change option values by editing a list of options.

M-x list-options displays a list of all Emacs option variables, in an Emacs buffer named ‘*List Options*’. Each option is shown with its documentation and its current value. Here is what a portion of it might look like:

;; exec-path:
("." "/usr/local/bin" "/usr/ucb" "/bin" "/usr/bin" "/u2/emacs/etc")
*List of directories to search programs to run in subprocesses.
Each element is a string (directory name)
or nil (try the default directory).
;;
;; fill-column:
75
*Column beyond which automatic line-wrapping should happen.
Automatically becomes buffer-local when set in any fashion.
;;

M-x edit-options goes one step further and immediately selects the ‘*List Options*’ buffer; this buffer uses the major mode Options mode, which provides commands that allow you to point at an option and change its value:

s

Set the variable point is in or near to a new value read using the minibuffer.

x

Toggle the variable point is in or near: if the value was nil, it becomes t; otherwise it becomes nil.

1

Set the variable point is in or near to t.

0

Set the variable point is in or near to nil.

n
p

Move to the next or previous variable.

Any changes take effect immediately, and last until you exit from Emacs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.3 Hooks

A hook is a variable where you can store a function or functions to be called on a particular occasion by an existing program. Emacs provides a number of hooks for the sake of customization.

Most of the hooks in Emacs are normal hooks. These variables contain lists of functions to be called with no arguments. The reason most hooks are normal hooks is so that you can use them in a uniform way. Every variable in Emacs whose name ends in ‘-hook’ is a normal hook.

Most major modes run hooks as the last step of initialization. This makes it easy for a user to customize the behavior of the mode, by overriding the local variable assignments already made by the mode. But hooks may also be used in other contexts. For example, the hook suspend-hook runs just before Emacs suspends itself (@pxref{Exiting}).

The recommended way to add a hook function to a normal hook is by calling add-hook. You can use any valid Lisp function as the hook function. For example, here’s how to set up a hook to turn on Auto Fill mode when entering Text mode and other modes based on Text mode:

(add-hook 'text-mode-hook 'turn-on-auto-fill)

The next example shows how to use a hook to customize the indentation of C code. (People often have strong personal preferences for one format compared to another.) Here the hook function is an anonymous lambda expression.

(add-hook 'c-mode-hook 
  (function (lambda ()
              (setq c-indent-level 4
                    c-argdecl-indent 0
                    c-label-offset -4
                    c-continued-statement-indent 0
                    c-brace-offset 0
                    comment-column 40))))

(setq c++-mode-hook c-mode-hook)

It is best to design your hook functions so that the order in which they are executed does not matter. Any dependence on the order is “asking for trouble.” However, the order is predictable: the most recently added hook functions are executed first.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.4 Local Variables

M-x make-local-variable <RET> var <RET>

Make variable var have a local value in the current buffer.

M-x kill-local-variable <RET> var <RET>

Make variable var use its global value in the current buffer.

M-x make-variable-buffer-local <RET> var <RET>

Mark variable var so that setting it will make it local to the buffer that is current at that time.

Any variable can be made local to a specific Emacs buffer. This means that its value in that buffer is independent of its value in other buffers. A few variables are always local in every buffer. Every other Emacs variable has a global value which is in effect in all buffers that have not made the variable local.

M-x make-local-variable reads the name of a variable and makes it local to the current buffer. Further changes in this buffer will not affect others, and further changes in the global value will not affect this buffer.

M-x make-variable-buffer-local reads the name of a variable and changes the future behavior of the variable so that it will become local automatically when it is set. More precisely, once a variable has been marked in this way, the usual ways of setting the variable automatically do make-local-variable first. We call such variables per-buffer variables.

Major modes (@pxref{Major Modes}) always make the variables they set local to the buffer. This is why changing major modes in one buffer has no effect on other buffers. Minor modes also work by setting variables—normally, each minor mode has one controlling variable which is non-nil when the mode is enabled (see section Minor Modes). For most minor modes, the controlling variable is per buffer.

Emacs contains a number of variables that are always per-buffer. These include abbrev-mode, auto-fill-function, case-fold-search, comment-column, ctl-arrow, fill-column, fill-prefix, indent-tabs-mode, left-margin, mode-line-format, overwrite-mode,
selective-display-ellipses, selective-display, tab-width, and truncate-lines. Some other variables are always local in every buffer, but they are used for internal purposes.

M-x kill-local-variable reads the name of a variable and makes it cease to be local to the current buffer. The global value of the variable henceforth is in effect in this buffer. Setting the major mode kills all the local variables of the buffer except for a few specially marked variables that are permanent locals.

To set the global value of a variable, regardless of whether the variable has a local value in the current buffer, you can use the Lisp function setq-default. It works like setq. If there is a local value in the current buffer, the local value is not affected by setq-default; thus, the new global value may not be visible until you switch to another buffer. For example,

(setq-default fill-column 75)

setq-default is the only way to set the global value of a variable that has been marked with make-variable-buffer-local.

Lisp programs can look at a variable’s default value with default-value. This function takes a symbol as argument and returns its default value. The argument is evaluated; usually you must quote it explicitly. For example,

(default-value 'fill-column)

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2.5 Local Variables in Files

A file can specify local variable values for use when you edit the file with Emacs. Visiting the file checks for local variables specifications; it automatically makes these variables local to the buffer, and sets them to the values specified in the file.

There are two ways to specify local variable values: in the first line, or with a local variables list. Here’s how to do this with the first line:

-*- mode: modename; var: value; … -*-

You can specify any number of variables/value pairs in this way, each pair with a colon and semicolon as shown above. The major mode should come first, if it is mentioned at all. Here is an example that specifies Lisp mode and sets two variables with numeric values:

;; -*-Mode: Lisp; fill-column: 75; comment-column: 50; -*-

A local variables list goes near the end of the file, in the last page. (It is often best to put it on a page by itself.) The local variables list starts with a line containing the string ‘Local Variables:’, and ends with a line containing the string ‘End:’. In between come the variable names and values, one set per line, as ‘variable: value’. The values are not evaluated; they are used literally.

Here is an example of a local variables list:

;;; Local Variables: ***
;;; mode:lisp ***
;;; comment-column:0 ***
;;; comment-start: ";;; "  ***
;;; comment-end:"***" ***
;;; End: ***

As you see, each line starts with the prefix ‘;;; ’ and each line ends with the suffix ‘ ***’. Emacs recognizes these as the prefix and suffix based on the first line of the list, by finding them surrounding the magic string ‘Local Variables:’; so it automatically discards them from the other lines of the list.

The usual reason for using a prefix and/or suffix is to embed the local variables list in a comment, so it won’t confuse other programs that the file is intended as input for. The example above is for a language where comment lines start with ‘;;; ’ and end with ‘***’; the local values for comment-start and comment-end customize the rest of Emacs for this unusual syntax. Don’t use a prefix (or a suffix) if you don’t need one.

Two “variable names” have special meanings in a local variables list: a value for the variable mode really sets the major mode, and a value for the variable eval is simply evaluated as an expression and the value is ignored. mode and eval are not real variables; setting such variables in any other context has no such effect. If mode is used in a local variables list, it should be the first entry in the list.

The start of the local variables list must be no more than 3000 characters from the end of the file, and must be in the last page if the file is divided into pages. Otherwise, Emacs will not notice it is there. The purpose of this is so that a stray ‘Local Variables:’ not in the last page does not confuse Emacs, and so that visiting a long file that is all one page and has no local variables list need not take the time to search the whole file.

You may be tempted to try to turn on Auto Fill mode with a local variable list. That is a mistake. The choice of Auto Fill mode or not is a matter of individual taste, not a matter of the contents of particular files. If you want to use Auto Fill, set up major mode hooks with your ‘.emacs’ file to turn it on (when appropriate) for you alone (see section The Init File, ‘~/.emacs). Don’t try to use a local variable list that would impose your taste on everyone.

The variable enable-local-variables controls whether to process local variables lists, and thus gives you a chance to override them. Its default value is t, which means to process local variables lists. If you set the value to nil, Emacs simply ignores local variables lists. Any other value says to query you about each local variables list, showing you the local variables list to consider.

The eval “variable” creates special risks, so there is a separate variable enable-local-eval to control whether Emacs processes eval variables. The three possibilities for the value are t, nil, and anything else, just as for enable-local-variables. The default is maybe, which is neither t nor nil, so normally Emacs queries about eval variable settings.

Use the command normal-mode to reset the local variables and major mode of a buffer according to the file name and contents, including the local variables list if any. @xref{Choosing Modes}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3 Keyboard Macros

A keyboard macro is a command defined by the user to abbreviate a sequence of keys. For example, if you discover that you are about to type C-n C-d forty times, you can speed your work by defining a keyboard macro to do C-n C-d and calling it with a repeat count of forty.

C-x (

Start defining a keyboard macro (start-kbd-macro).

C-x )

End the definition of a keyboard macro (end-kbd-macro).

C-x e

Execute the most recent keyboard macro (call-last-kbd-macro).

C-u C-x (

Re-execute last keyboard macro, then add more keys to its definition.

C-x q

When this point is reached during macro execution, ask for confirmation (kbd-macro-query).

M-x name-last-kbd-macro

Give a command name (for the duration of the session) to the most recently defined keyboard macro.

M-x insert-kbd-macro

Insert in the buffer a keyboard macro’s definition, as Lisp code.

Keyboard macros differ from ordinary Emacs commands in that they are written in the Emacs command language rather than in Lisp. This makes it easier for the novice to write them, and makes them more convenient as temporary hacks. However, the Emacs command language is not powerful enough as a programming language to be useful for writing anything intelligent or general. For such things, Lisp must be used.

You define a keyboard macro while executing the commands which are the definition. Put differently, as you define a keyboard macro, the definition is being executed for the first time. This way, you can see what the effects of your commands are, so that you don’t have to figure them out in your head. When you are finished, the keyboard macro is defined and also has been, in effect, executed once. You can then do the whole thing over again by invoking the macro.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.1 Basic Use

To start defining a keyboard macro, type the C-x ( command (start-kbd-macro). From then on, your keys continue to be executed, but also become part of the definition of the macro. ‘Def’ appears in the mode line to remind you of what is going on. When you are finished, the C-x ) command (end-kbd-macro) terminates the definition (without becoming part of it!). For example

C-x ( M-f foo C-x )

defines a macro to move forward a word and then insert ‘foo’.

The macro thus defined can be invoked again with the C-x e command (call-last-kbd-macro), which may be given a repeat count as a numeric argument to execute the macro many times. C-x ) can also be given a repeat count as an argument, in which case it repeats the macro that many times right after defining it, but defining the macro counts as the first repetition (since it is executed as you define it). So, giving C-x ) an argument of 4 executes the macro immediately 3 additional times. An argument of zero to C-x e or C-x ) means repeat the macro indefinitely (until it gets an error or you type C-g).

If you wish to repeat an operation at regularly spaced places in the text, define a macro and include as part of the macro the commands to move to the next place you want to use it. For example, if you want to change each line, you should position point at the start of a line, and define a macro to change that line and leave point at the start of the next line. Then repeating the macro will operate on successive lines.

After you have terminated the definition of a keyboard macro, you can add to the end of its definition by typing C-u C-x (. This is equivalent to plain C-x ( followed by retyping the whole definition so far. As a consequence it re-executes the macro as previously defined.

You can use function keys in a keyboard macro, just like keyboard keys. You can even use mouse events, but be careful about that: when the macro replays the mouse event, it uses the original mouse position of that event, the position that the mouse had while you were defining the macro. The effect of this may be hard to predict. (Using the current mouse position would be even less predictable.)

One thing that doesn’t always work well in a keyboard macro is the command C-M-c (exit-recursive-edit). When this command exits a recursive edit that started within the macro, it works as you’d expect. But if it exits a recursive edit that started before you invoked the keyboard macro, it also necessarily exits the keyboard macro as part of the process.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.2 Naming and Saving Keyboard Macros

If you wish to save a keyboard macro for longer than until you define the next one, you must give it a name using M-x name-last-kbd-macro. This reads a name as an argument using the minibuffer and defines that name to execute the macro. The macro name is a Lisp symbol, and defining it in this way makes it a valid command name for calling with M-x or for binding a key to with global-set-key (see section Keymaps). If you specify a name that has a prior definition other than another keyboard macro, an error message is printed and nothing is changed.

Once a macro has a command name, you can save its definition in a file. Then it can be used in another editing session. First, visit the file you want to save the definition in. Then use this command:

M-x insert-kbd-macro <RET> macroname <RET>

This inserts some Lisp code that, when executed later, will define the same macro with the same definition it has now. (You need not understand Lisp code to do this, because insert-kbd-macro writes the Lisp code for you.) Then save the file. You can load the file later with load-file (@pxref{Lisp Libraries}). If the file you save in is your init file ‘~/.emacs’ (see section The Init File, ‘~/.emacs) then the macro will be defined each time you run Emacs.

If you give insert-kbd-macro a prefix argument, it makes additional Lisp code to record the keys (if any) that you have bound to the keyboard macro, so that the macro will be reassigned the same keys when you load the file.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.3 Executing Macros with Variations

Using C-x q (kbd-macro-query), you can get an effect similar to that of query-replace, where the macro asks you each time around whether to make a change. When you are defining the macro, type C-x q at the point where you want the query to occur. During macro definition, the C-x q does nothing, but when you run the macro later, C-x q asks you interactively whether to continue.

The valid responses when C-x q asks are <SPC> (or y), <DEL> (or n), <ESC> (or q), C-l and C-r. The answers are the same as in query replace, though not all of the query-replace options are meaningful.

Specifically, <SPC> means to continue. <DEL> means to skip the remainder of this repetition of the macro and start right away with the next repetition. <ESC> means to skip the remainder of this repetition and cancel further repetition. C-l redraws the screen and asks you again for a character to say what to do.

C-r enters a recursive editing level, in which you can perform editing which is not part of the macro. When you exit the recursive edit using C-M-c, you are asked again how to continue with the keyboard macro. If you type a <SPC> at this time, the rest of the macro definition is executed. It is up to you to leave point and the text in a state such that the rest of the macro will do what you want.

C-u C-x q, which is C-x q with a numeric argument, performs a different function. It enters a recursive edit reading input from the keyboard, both when you type it during the definition of the macro, and when it is executed from the macro. During definition, the editing you do inside the recursive edit does not become part of the macro. During macro execution, the recursive edit gives you a chance to do some particularized editing. @xref{Recursive Edit}.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4 Customizing Key Bindings

This section describes key bindings which map keys to commands, and the keymaps which record key bindings. It also explains how to customize key bindings.

Recall that a command is a Lisp function whose definition provides for interactive use. Like every Lisp function, a command has a function name which usually consists of lower case letters and hyphens.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.1 Keymaps

The bindings between key sequences and command functions are recorded in data structures called keymaps. Emacs has many of these, each used on particular occasions.

Recall that a key sequence (key, for short) is a sequence of input events that have a meaning as a unit. Input events include characters, function keys and mouse buttons—all the inputs that you can send to the computer with your terminal. A key sequence gets its meaning from its binding, which says what command it runs. The function of keymaps is to record these bindings.

The global keymap is the most important keymap because it is always in effect. The global keymap defines keys for Fundamental mode; most of these definitions are common to all (or most) major modes. Each major or minor mode can have its own keymap which overrides the definitions of some keys.

For example, a self-inserting character such as g is self-inserting because the global keymap binds it to the command self-insert-command. The standard Emacs editing characters such as C-a also get their standard meanings from the global keymap. Commands to rebind keys, such as M-x global-set-key, actually work by storing the new binding in the proper place in the global map. See section Changing Key Bindings Interactively.

Meta characters work differently; Emacs translates each Meta character into a pair of characters starting with <ESC>. When you type the character M-a in a key sequence, Emacs replaces it with <ESC> a. A meta key comes in as a single input event, but becomes two events for purposes of key bindings. The reason for this is historical, and we might change in someday.

Most modern keyboards have function keys as well as character keys. Function keys send input events just as character keys do, and keymaps can have bindings for them.

On many terminals, typing a function key actually sends the computer a sequence of characters; the precise details of the sequence depends on which function key and on the model of terminal you are using. (Often he sequence starts with <ESC> [.) If Emacs understands your terminal type properly, it recognizes the character sequences forming function keys wherever they occur in a key sequence (not just at the beginning). Thus, for most purposes, you can pretend the function keys reach Emacs directly and ignore their encoding as character sequences.

Mouse buttons also produce input events. These events come with other data—the window and position where you pressed or released the button, and a timestamp. But only the choice of button matters for key bindings; the other data matters only if a command looks at it. (Commands designed for mouse invocation usually do look at the other data.)

A keymap records definitions for single events. Interpreting a key sequence of multiple events involves a chain of keymaps. The first keymap gives a definition for the first event; this definition is another keymap, which is used to look up the second event in the sequence, and so on.

Key sequences can mix function keys and characters. For example, C-x <SELECT> makes sense. If you make <SELECT> a prefix key, then <SELECT> C-n makes sense. You can even mix mouse events with keyboard events, but we recommend against it, because such sequences are inconvenient to type in.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.2 Prefix Keymaps

A prefix key such as C-x or <ESC> has its own keymap, which holds the definition for the event that immediately follows that prefix.

The definition of a prefix key is the keymap to use for looking up the following event. The definition can also be a Lisp symbol whose function definition is the following keymap; the effect is the same, but it provides a command name for the prefix key that can be used as a description of what the prefix key is for. Thus, the binding of C-x is the symbol Ctl-X-Prefix, whose function definition is the keymap for C-x commands. The definitions of C-c, C-x, C-h and <ESC> as prefix keys appear in the global map, so these prefix keys are always available.

Some prefix keymaps are stored in variables with names:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.3 Local Keymaps

So far we have explained the ins and outs of the global map. Major modes customize Emacs by providing their own key bindings in local keymaps. For example, C mode overrides <TAB> to make it indent the current line for C code. Portions of text in the buffer can specify their own keymaps to substitute for the keymap of the buffer’s major mode.

Minor modes can also have local keymaps. Whenever a minor mode is in effect, the definitions in its keymap override both the major mode’s local keymap and the global keymap.

The local keymaps for Lisp mode, C mode, and several other major modes always exist even when not in use. These are kept in variables named lisp-mode-map, c-mode-map, and so on. For major modes less often used, the local keymap is normally constructed only when the mode is used for the first time in a session. This is to save space.

All minor mode keymaps are created in advance. There is no way to defer their creation until the minor mode is enabled.

A local keymap can locally redefine a key as a prefix key by defining it as a prefix keymap. If the key is also defined globally as a prefix, then its local and global definitions (both keymaps) effectively combine: both of them are used to look up the event that follows the prefix key. Thus, if the mode’s local keymap defines C-c as another keymap, and that keymap defines C-z as a command, this provides a local meaning for C-c C-z. This does not affect other sequences that start with C-c; If those sequences don’t have their own local bindings, their global bindings remain in effect.

Another way to think of this is that Emacs handles a multi-event key sequence by looking in several keymaps, one by one, for a binding of the whole key sequence. First it checks the minor mode keymaps for minor modes that are enabled, then it checks the major mode’s keymap, and then it checks the global keymap. This is not precisely how key lookup works, but it’s good enough for understanding ordinary circumstances.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.4 Minibuffer Keymaps

The minibuffer has its own set of local keymaps; they contain various completion and exit commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.5 Changing Key Bindings Interactively

The way to redefine an Emacs key is to change its entry in a keymap. You can change the global keymap, in which case the change is effective in all major modes (except those that have their own overriding local definitions for the same key). Or you can change the current buffer’s local map, which affects all buffers using the same major mode.

M-x global-set-key <RET> key cmd <RET>

Define key globally to run cmd.

M-x local-set-key <RET> key cmd <RET>

Define key locally (in the major mode now in effect) to run cmd.

M-x global-unset-key <RET> key

Make key undefined in the global map.

M-x local-unset-key <RET> key

Make key undefined locally (in the major mode now in effect).

For example, suppose you like to execute commands in a subshell within an Emacs buffer, instead of suspending Emacs and executing commands in your login shell. Normally, C-z is bound to the function suspend-emacs, but you can change C-z to invoke an interactive subshell within Emacs, by binding it to shell as follows:

M-x global-set-key <RET> C-z shell <RET>

global-set-key reads the command name after the key. After you press the key, a message like this appears so that you can confirm that you are binding the key you want:

Set key C-z to command: 

You can redefine function keys and mouse events in the same way; just type the function key or click the mouse when it’s time to specify the key to rebind.

You can rebind a key that contains more than one event in the same way. Emacs keeps reading the key to rebind until it is a complete key (that is, not a prefix key). Thus, if you type C-f for key, that’s the end; the minibuffer is entered immediately to read cmd. But if you type C-x, another character is read; if that is 4, another character is read, and so on. For example,

M-x global-set-key <RET> C-x 4 $ spell-other-window <RET>

would redefine C-x 4 $ to run the (fictitious) command spell-other-window.

You can remove the global definition of a key with global-unset-key. This makes the key undefined; if you type it, Emacs will just beep. Similarly, local-unset-key makes a key undefined in the current major mode keymap, which makes the global definition (or lack of one) come back into effect in that major mode.

If you have redefined (or undefined) a key and you subsequently wish to retract the change, undefining the key will not do the job—you need to redefine the key with its standard definition. To find the name of the standard definition of a key, go to a Fundamental mode buffer and use C-h c. The documentation of keys in this manual also lists their command names.

If you want to prevent yourself from invoking a command by mistake, it is better to disable the command than to undefine the key. A disabled command is less work to invoke when you really want to. See section Disabling Commands.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.6 Rebinding Keys in Your Init File

If you have a set of default definitions that you like to use all the time, you can put commands in your ‘.emacs’ file by using their Lisp syntax. Thus, the first global-set-key command in this section could be put in an ‘.emacs’ file in either of the two following formats:

(global-set-key "\C-z" 'shell)

or as:

(global-set-key [?\C-z] 'shell)

When the key sequence consists of characters, like this one, you can write it as a string or as a vector. The first format specifies the key sequence as a string, "\C-z". The second format uses a vector to specify the key sequence. The square brackets (‘[…]’) delimit the contents of the vector. The vector in this example contains just one element, which is the integer code corresponding to C-z. The question mark is the Lisp syntax for a character constant; the character must follow with no intervening spaces.

The single-quote before shell marks it as a constant symbol rather than a variable. If you omit the quote, Emacs tries to evaluate shell immediately as a variable. This probably causes an error; it certainly isn’t what you want.

Here is another example that binds a key sequence two characters long:

(global-set-key "\C-xl" 'make-symbolic-link)

or:

(global-set-key [?\C-x ?l] 'make-symbolic-link)

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.7 Rebinding Function Keys

Key sequences can contain function keys as well as ordinary characters. Just as Lisp characters (actually integers) represent keyboard characters, Lisp symbols represent function keys. If the function key has a word as its label, then that word is also the name of the corresponding Lisp symbol. Here are the Lisp names for other function keys:

left, up, right, down

Cursor arrow keys.

begin, end, home, next, prior

Other cursor repositioning keys.

select, print, execute, backtab
insert, undo, redo, clearline
insertline, deleteline, insertchar, deletechar,

Miscellaneous function keys.

f1f35

Numbered function keys (across the top of the keyboard).

kp-add, kp-subtract, kp-multiply, kp-divide
kp-backtab, kp-space, kp-tab, kp-enter
kp-separator, kp-decimal, kp-equal

Keypad keys (to the right of the regular keyboard), with names or punctuation.

kp-0, kp-1, … kp-9

Keypad keys with digits.

kp-f1, kp-f2, kp-f3, kp-f4

Keypad PF keys.

A key sequence which contains non-characters must be a vector rather than a string. To write a vector, write square brackets containing the vector elements. Write spaces to separate the elements. If an element is a symbol, simply write the symbol’s name—no delimiters or punctuation are needed. If an element is a character, write a Lisp character constant, which is ‘?’ followed by the character as it would appear in a string.

Thus, to bind function key ‘f1’ to the command rmail, write the following:

(global-set-key [f1] 'rmail)

To bind the right-arrow key to the command forward-char, you can use this expression:

(global-set-key [right] 'forward-char)

using the Lisp syntax for a vector containing the symbol right. (This binding is present in Emacs by default.)

You can mix function keys and characters in a key sequence. This example binds C-x <RIGHT> to the command forward-page.

(global-set-key [?\C-x right] 'forward-page)

where ?\C-x is the Lisp character constant for the character C-x. The vector element right is a symbol and therefore does not take a question mark.

You can use the modifier keys <CTRL>, <META>, <HYPER>, <SUPER>, <ALT> and <SHIFT> with function keys. To represent these modifiers, prepend the strings ‘C-’, ‘M-’, ‘H-’, ‘s-’, ‘A-’ and ‘S-’ to the symbol name. Thus, here is how to make Hyper-Meta-<RIGHT> move forward a word:

(global-set-key [H-M-right] 'forward-word)

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.8 Rebinding Mouse Buttons

Emacs uses Lisp symbols to designate mouse buttons, too. The ordinary mouse events in Emacs are click events; these happen when you press a button and release it without moving the mouse. You can also get drag events, when you move the mouse while holding the button down. Drag events happen when you finally let go of the button.

The symbols for basic click events are mouse-1 for the leftmost button, mouse-2 for the next, and so on. Here is how you can redefine the second mouse button to split the current window:

(global-set-key [mouse-2] 'split-window-vertically)

The symbols for drag events are similar, but have the prefix ‘drag-’ before the word ‘mouse’. For example, dragging the left button generates a drag-mouse-1 event.

You can also request events when the mouse button is pressed down. These events start with ‘down-’ instead of ‘drag-’. Such events are generated only if they have key bindings. When you get a button-down event, a corresponding click or drag event will always follow.

The symbols for mouse events also indicate the status of the modifier keys, with the usual prefixes ‘C-’, ‘M-’, ‘H-’, ‘s-’, ‘A-’ and ‘S-’. These always follow ‘drag-’ or ‘down-’.

A frame includes areas that don’t show text from the buffer, such as the mode line and the scroll bar. You can tell whether a mouse button comes from a special area of the screen by means of dummy “prefix keys.” For example, if you click the mouse in the mode line, you get the prefix key mode-line before the ordinary mouse-button symbol. Thus, here is how to define the command for clicking the left button in a mode line to run scroll-up:

(global-set-key [mode-line mouse-1] 'scroll-up)

Here is the complete list of these dummy prefix keys and their meanings:

mode-line

The mouse was in the mode line of a window.

vertical-line

The mouse was in the vertical line separating side-by-side windows.

vertical-scroll-bar

The mouse was in a horizontal scroll bar. This is the kind of scroll bar people normally use.

horizontal-scroll-bar

The mouse was in a horizontal scroll bar. Horizontal scroll bars do horizontal scrolling, and people don’t use them often.

You can put more than one mouse button in a key sequence, but it isn’t usual to do so.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4.9 Disabling Commands

Disabling a command marks the command as requiring confirmation before it can be executed. The purpose of disabling a command is to prevent beginning users from executing it by accident and being confused.

Attempting to invoke a disabled command interactively in Emacs causes the display of a window containing the command’s name, its documentation, and some instructions on what to do immediately; then Emacs asks for input saying whether to execute the command as requested, enable it and execute, or cancel it. If you decide to enable the command, you are asked whether to do this permanently or just for the current session. Enabling permanently works by automatically editing your ‘.emacs’ file.

The direct mechanism for disabling a command is to have a non-nil disabled property on the Lisp symbol for the command. Here is the Lisp program to do this:

(put 'delete-region 'disabled t)

If the value of the disabled property is a string, that string is included in the message printed when the command is used:

(put 'delete-region 'disabled
     "Text deleted this way cannot be yanked back!\n")

You can make a command disabled either by editing the ‘.emacs’ file directly or with the command M-x disable-command, which edits the ‘.emacs’ file for you. Likewise, M-x enable-command edits ‘.emacs’ to enable a command permanently. See section The Init File, ‘~/.emacs.

Whether a command is disabled is independent of what key is used to invoke it; it also applies if the command is invoked using M-x. Disabling a command has no effect on calling it as a function from Lisp programs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.5 Keyboard Translations

Some keyboards do not make it convenient to send all the special characters that Emacs uses. The most common problem case is the <DEL> character. Some keyboards provide no convenient way to type this very important character—usually because they were designed to expect the character C-h to be used for deletion. On these keyboard, if you press the key normally used for deletion, Emacs handles the C-h as a prefix character and offers you a list of help options, which is not what you want.

You can work around this problem within Emacs by setting up keyboard translations to turn C-h into <DEL> and <DEL> into C-h, as follows:

;; Translate C-h to <DEL>.
(keyboard-translate ?\C-h ?\C-?)
;; Translate <DEL> to C-h.
(keyboard-translate ?\C-? ?\C-h)

Keyboard translations are not the same as key bindings in keymaps (see section Keymaps). Emacs contains numerous keymaps that apply in different situations, but there is only one set of keyboard translations, and it applies to every character that Emacs reads from the terminal. Keyboard translations take place at the lowest level of input processing; the keys that are looked up in keymaps contain the characters that result from keyboard translation.

For full information about how to use keyboard translations, see Translating Input in The Emacs Lisp Reference Manual.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6 The Syntax Table

All the Emacs commands which parse words or balance parentheses are controlled by the syntax table. The syntax table says which characters are opening delimiters, which are parts of words, which are string quotes, and so on. Each major mode has its own syntax table (though sometimes related major modes use the same one) which it installs in each buffer that uses that major mode. The syntax table installed in the current buffer is the one that all commands use, so we call it “the” syntax table. A syntax table is a Lisp object, a vector of length 256 whose elements are numbers.

To display a description of the contents of the current syntax table, type C-h s (describe-syntax). The description of each character includes both the string you would have to give to modify-syntax-entry to set up that character’s current syntax, and some English to explain that string if necessary.

For full information on the syntax table, see Syntax Table in The Emacs Lisp Reference Manual.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7 The Init File, ‘~/.emacs

When Emacs is started, it normally loads a Lisp program from the file ‘.emacs’ in your home directory. We call this file your init file because it specifies how to initialize Emacs for you. You can use the command line switches ‘-q’ and ‘-u’ to tell Emacs whether to load an init file, and which one (@pxref{Entering Emacs}).

There can also be a default init file, which is the library named ‘default.el’, found via the standard search path for libraries. The Emacs distribution contains no such library; your site may create one for local customizations. If this library exists, it is loaded whenever you start Emacs (except when you specify ‘-q’). But your init file, if any, is loaded first; if it sets inhibit-default-init non-nil, then ‘default’ is not loaded.

If you have a large amount of code in your ‘.emacs’ file, you should move it into another file such as ‘~/something.el’, byte-compile it, and make your ‘.emacs’ file load it with (load "~/something"). See Byte Compilation in the Emacs Lisp Reference Manual, for more information about compiling Emacs Lisp programs.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.1 Init File Syntax

The ‘.emacs’ file contains one or more Lisp function call expressions. Each of these consists of a function name followed by arguments, all surrounded by parentheses. For example, (setq fill-column 60) calls the function setq to set the variable fill-column (@pxref{Filling}) to 60.

The second argument to setq is an expression for the new value of the variable. This can be a constant, a variable, or a function call expression. In ‘.emacs’, constants are used most of the time. They can be:

Numbers:

Numbers are written in decimal, with an optional initial minus sign.

Strings:

Lisp string syntax is the same as C string syntax with a few extra features. Use a double-quote character to begin and end a string constant.

In a string, you can include newlines and special characters literally. But often it is cleaner to use backslash sequences for them: ‘\n’ for newline, ‘\b’ for backspace, ‘\r’ for carriage return, ‘\t’ for tab, ‘\f’ for formfeed (control-L), ‘\e’ for escape, ‘\\’ for a backslash, ‘\"’ for a double-quote, or ‘\ooo’ for the character whose octal code is ooo. Backslash and double-quote are the only characters for which backslash sequences are mandatory.

\C-’ can be used as a prefix for a control character, as in ‘\C-s’ for ASCII control-S, and ‘\M-’ can be used as a prefix for a Meta character, as in ‘\M-a’ for Meta-A or ‘\M-\C-a’ for Control-Meta-A.

Characters:

Lisp character constant syntax consists of a ‘?’ followed by either a character or an escape sequence starting with ‘\’. Examples: ?x, ?\n, ?\", ?\). Note that strings and characters are not interchangeable in Lisp; some contexts require one and some contexts require the other.

True:

t stands for ‘true’.

False:

nil stands for ‘false’.

Other Lisp objects:

Write a single-quote (’) followed by the Lisp object you want.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.2 Init File Examples

Here are some examples of doing certain commonly desired things with Lisp expressions:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.3 Terminal-specific Initialization

Each terminal type can have a Lisp library to be loaded into Emacs when it is run on that type of terminal. For a terminal type named termtype, the library is called ‘term/termtype’ and it is found by searching the directories load-path as usual and trying the suffixes ‘.elc’ and ‘.el’. Normally it appears in the subdirectory ‘term’ of the directory where most Emacs libraries are kept.

The usual purpose of the terminal-specific library is to define the escape sequences used by the terminal’s function keys using the library ‘keypad.el’. See the file ‘term/vt100.el’ for an example of how this is done.

When the terminal type contains a hyphen, only the part of the name before the first hyphen is significant in choosing the library name. Thus, terminal types ‘aaa-48’ and ‘aaa-30-rv’ both use the library ‘term/aaa’. The code in the library can use (getenv "TERM") to find the full terminal type name.

The library’s name is constructed by concatenating the value of the variable term-file-prefix and the terminal type. Your ‘.emacs’ file can prevent the loading of the terminal-specific library by setting term-file-prefix to nil.

Emacs runs the hook term-setup-hook at the end of initialization, after both your ‘.emacs’ file and any terminal-specific library have been read in. Add hook functions to this hook if you wish to override part of any of the terminal-specific libraries and to define initializations for terminals that do not have a library. See section Hooks.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7.4 How Emacs Finds Your Init File

Normally Emacs uses the environment variable HOME to find ‘.emacs’; that’s what ‘~’ means in a file name. But if you have done su, Emacs tries to find your own ‘.emacs’, not that of the user you are currently pretending to be. The idea is that you should get your own editor customizations even if you are running as the super user.

More precisely, Emacs first determines which user’s init file to use. It gets the user name from the environment variables USER and LOGNAME; if neither of those exists, it uses effective user-ID. If that user name matches the real user-ID, then Emacs uses HOME; otherwise, it looks up the home directory corresponding to that user name in the system’s data base of users.


[Top] [Contents] [Index] [ ? ]

About This Document

This document was generated on March 29, 2022 using texi2html 5.0.

The buttons in the navigation panels have the following meaning:

Button Name Go to From 1.2.3 go to
[ << ] FastBack Beginning of this chapter or previous chapter 1
[ < ] Back Previous section in reading order 1.2.2
[ Up ] Up Up section 1.2
[ > ] Forward Next section in reading order 1.2.4
[ >> ] FastForward Next chapter 2
[Top] Top Cover (top) of document  
[Contents] Contents Table of contents  
[Index] Index Index  
[ ? ] About About (help)  

where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:


This document was generated on March 29, 2022 using texi2html 5.0.